using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using SqlCeViewer.Base;
using SqlCeViewer.CommonMethod;
using SqlCeViewer.MainForm;
using System.IO;
using SqlCeViewer.Utility;
using CustomControl.NewXLAGControl;
using System.Data.SqlServerCe;
using SqlCeViewer.UI;
using SqlCeViewer.Moduls;

namespace SqlCeViewer
{
    public partial class NewLoginForm :BaseSubForm
    {
        public NewLoginForm()
        {
#if DEBUG
            GlobalInfo.log.LogLineMsg("Entry Main UI");
#else 
#endif
            InitializeComponent();

#if DEBUG
            GlobalInfo.log.LogLineMsg("Do Init ok ");
#else
#endif

            this.Shown += new EventHandler(NewLoginForm_Shown);
            
            InitSelf();

#if DEBUG
            GlobalInfo.log.LogLineMsg("Init Self OK ");
#else
#endif

        }

        void NewLoginForm_Shown(object sender, EventArgs e)
        {
            BringToFront();
        }

        private void InitSelf()
        {
            //this.AllowDrop = true;
            //this.Drop += new DragEventHandler(AppEntry_Drop);
            GlobalInfo._curHistoryList = new List<string>();
            RefreshLastOpenedDbsStatus();
            OpenModeClass op1 = new OpenModeClass();
            op1.mode = OpenMode.ReadWrite;
            op1.modeDisplayName = "Read Write";

            OpenModeClass op2 = new OpenModeClass();
            op2.mode = OpenMode.ReadOnly;
            op2.modeDisplayName = "Read Only";

            OpenModeClass op3 = new OpenModeClass();
            op3.mode = OpenMode.SharedRead;
            op3.modeDisplayName = "Shared Read";

            OpenModeClass op4 = new OpenModeClass();
            op4.mode = OpenMode.Exclusive;
            op4.modeDisplayName = "Exclusive";

            this.comboBox1.Properties.Items.Add(op1);
            this.comboBox1.Properties.Items.Add(op2);
            this.comboBox1.Properties.Items.Add(op3);
            this.comboBox1.Properties.Items.Add(op4);

            this.comboBox1.SelectedIndex = 0;

            this.txtPwd.Properties.PasswordChar = '*';
            this.txtPwd.KeyDown += new KeyEventHandler(txtPwd_KeyDown);
        }

        void txtPwd_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                butOpen_Click(null, null);
            }
        }


        private void but_SelectDB_Click(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            OpenFileDialog of = new OpenFileDialog();
            of.Filter = GlobalInfo.SQLCE_FILE_FILTER;
            if (of.ShowDialog() == DialogResult.OK)
            {
                this.txtDbPath.Text = of.FileName;
            }
        }

        private void butOpen_Click(object sender, EventArgs e)
        {

            string dbName = txtDbPath.Text;
            string dbPwd = txtPwd.Text;

            if (string.IsNullOrEmpty(dbName))
            {
                MessageBox.Show("Please input database name");
                return;
            }

            if (Utility.DetectNetworkDriver.IsPathOnNetworkDrive(dbName))
            {
                MessageBox.Show("SQLCE do not support open from network");
                return;
            }
            OpenModeClass CurOpenMode = null;
            if (comboBox1.SelectedItem == null)
            {
                CurOpenMode = comboBox1.Properties.Items[0] as OpenModeClass;
            }
            else
            {
                CurOpenMode = comboBox1.SelectedItem as OpenModeClass;
            }

            //If open db ok ,and get tables info ok , then do 
            //otherwise do nothing
            if (GlobalInfo.MainEngineer.OpenDatabase(dbName, txtPwd.Text, CurOpenMode))
            {
                this.Hide();
                this.Visible = false;
                txtDbPath.Text = string.Empty;
                txtPwd.Text = string.Empty;
                Properties.Settings.Default.LastestOpenedDb = dbName;
                Properties.Settings.Default.LastestOpenedDbPwd = dbPwd;
                Properties.Settings.Default.Save();

                if (!GlobalInfo._curHistoryList.Contains(dbName))
                {
                    GlobalInfo._curHistoryList.Add(dbName);

                    SerializeClass.SaveHistory(GlobalInfo._curHistoryList);
                }


                RefreshLastOpenedDbsStatus();

                

                switch (Properties.Settings.Default.StartMainIDEStep)
                {
                    case 0:
                        //mainIDE = new OLD_Main();
                        break;
                    case 1:
                        GlobalInfo.MainIDE = new Main();
                        GlobalInfo.MainIDE.MyHost.FormClosed += new FormClosedEventHandler(MyHost_FormClosed);
                        break;
                    default:
                        throw new Exception("Invalid mode");
                }

                GlobalInfo.MainIDE.MyHost.Tag = this;
                GlobalInfo.MainIDE.MyHost.WindowState = FormWindowState.Maximized;
                GlobalInfo.MainIDE.MyHost.BringToFront();
                GlobalInfo.MainIDE.MyHost.Show();
            }
        }

        void MyHost_FormClosed(object sender, FormClosedEventArgs e)
        {
            this.Visible = true;
            this.BringToFront();

        }
        private void butOpenLastest_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(Properties.Settings.Default.LastestOpenedDb))
            {
                return;
            }

            txtDbPath.Text = Properties.Settings.Default.LastestOpenedDb;
            txtPwd.Text = Properties.Settings.Default.LastestOpenedDbPwd;

            butOpen_Click(null, null);
        }

        private void butOpenHistory_Click(object sender, EventArgs e)
        {
            DynaControls.DbOpenedHistory history = new DynaControls.DbOpenedHistory();
            history.AfterSelectedValue += new DynaControls.DbOpenedHistory.Del_AfterSelectedValue(AfterSelect);

            history.ShowDialog();
        }

        private void AfterSelect(string args)
        {
            if (!string.IsNullOrEmpty(args))
            {
                this.txtDbPath.Text = args;
            }

        }
        private void butCreate_Click(object sender, EventArgs e)
        {
            CreateEmptyDb cb = new CreateEmptyDb();
            cb.CreateDbAfterSuccesful = new CreateEmptyDb.Del_CreateDbAfterSuccesful(RefreshAfterCreateSuccess);
            cb.ShowDialog();
        }
        private void RefreshAfterCreateSuccess(string dbFullPath, string pwd)
        {
            if (!string.IsNullOrEmpty(dbFullPath))
            {
                txtDbPath.Text = dbFullPath;

            }
            if (!string.IsNullOrEmpty(pwd))
            {
                txtPwd.Text = pwd;

            }

        }


        private void RefreshLastOpenedDbsStatus()
        {
            if (string.IsNullOrEmpty(Properties.Settings.Default.LastestOpenedDb))
            {

                butOpenLastest.Visible = false;
            }
            else
            {
                butOpenLastest.Visible = true;
            }

            if (!File.Exists(Config.DbHistoryFileFullPath))
            {

                this.butHistory.Visible = false;
            }
            else
            {
                this.butHistory.Visible = true;
                GlobalInfo._curHistoryList = SerializeClass.GetHistoryList();
            }

        }

        private void butImport_Click(object sender, EventArgs e)
        {
            DataExchange x = new DataExchange();
            x.ShowDialog();
        }

        private void butChangePwd_Click(object sender, EventArgs e)
        {

            string db = this.txtDbPath.Text;
            if (string.IsNullOrEmpty(db))
            {
                MessageBox.Show("Please select database first");
                return;
            }
            string oldPwd = txtPwd.Text;

            string newPwd = string.Empty;
            using (PopupForm p = new PopupForm())
            {
                p.X_NeedMask = true;
                p.X_NotifyStr = "New Password";
                if (p.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    newPwd = p.X_Result;
                }
                else
                {
                    return;
                }
            }

            try
            {
                using (SqlCeEngine eg = new SqlCeEngine())
                {
                    eg.LocalConnectionString = String.Format("Data Source={0};Password={1}", db, oldPwd);
                    eg.Compact(string.Format("Data Source={0};Password={1}", db, newPwd));
                }
            }
            catch (SqlCeException ee)
            {
                MessageBox.Show(String.Format("{0}\r\n{1}", ee.Message, "This may the old password you input is not valid"));
                return;
            }

            MessageBox.Show("Change password successful");
            txtPwd.Text = newPwd;

        }

        private void txtDbPath_DragDrop(object sender, DragEventArgs e)
        {
            
            //           e.Handled = true;
            if (e.Data.GetDataPresent(DataFormats.FileDrop, true))
            {
                string[] fileNames = e.Data.GetData(DataFormats.FileDrop, true) as string[];
                if (fileNames.Length == 1)
                {
                    // Check for a file (a directory will return false).
                    if (File.Exists(fileNames[0]))
                    {
                        // At this point we know there is a single file.
                        txtDbPath.Text = fileNames[0];
                    }
                }

            }
        }
    }
}